//
//  CZUserRegisterAccountViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/5.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZUserRegisterAccountViewController.h"
#import "CZUserLoginViewController.h"
#import "CZUserProtocolViewController.h"
#import "CZRegisterView.h"
#import "CZVerificationBtn.h"
@interface CZUserRegisterAccountViewController ()
@property (nonatomic, strong) YYTimer *timer;
@property (nonatomic, strong) CZRegisterView *registerView;
@end

@implementation CZUserRegisterAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"注册账号";
    [self getTopImage];
    CZRegisterView *registerView = [[[NSBundle mainBundle] loadNibNamed:@"CZRegisterView" owner:nil options:nil] firstObject];
    _registerView = registerView;
    [registerView.registerBtn addTarget:self action:@selector(accoutRegister) forControlEvents:(UIControlEventTouchUpInside)];
    [registerView.verificationCodeBtn addTarget:self action:@selector(getVerificationCode) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:registerView];
    [registerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [registerView.proBtn addTarget:self action:@selector(protocolAction) forControlEvents:(UIControlEventTouchUpInside)];
    // Do any additional setup after loading the view.
}

- (void)protocolAction {
    CZUserProtocolViewController *proVC = [[CZUserProtocolViewController alloc] init];
    [self.navigationController pushViewController:proVC animated:YES];
    
}

#pragma mark- 注册
- (void)accoutRegister {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user/register",APP_HOST];
    if (!_registerView.agreeBtn.selected) {
        [SVProgressHUD showErrorWithStatus:@"请阅读并同意用户协议"];
        return;
    }
    if (![self checkMobile]) {
        return;
    }
    if (_registerView.verificationCodeTextField.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的验证码"];
        return;
    }
    if (_registerView.passWordTextField.text.length < 6 || _registerView.passWordTextField.text.length > 12) {
        [SVProgressHUD showErrorWithStatus:@"请输入6位以上12位以下的密码"];
        return;
    }
    if (![_registerView.passWordTextField.text isEqualToString:_registerView.passWordAgainTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"两次输入密码不同"];
        return;
    }
    
    [GCZAFNetWorking POST:urlString params:@{@"login_id" : _registerView.phoneNumberTextField.text, @"code" : _registerView.verificationCodeTextField.text, @"pwd" : _registerView.passWordAgainTextField.text} success:^(NSDictionary *response) {
        DLog(@"%@", response[@"message"]);
        [SVProgressHUD showErrorWithStatus:response[@"message"]];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        DLog(@"获取验证码失败%@", error);
    }];
}

#pragma mark- 获取验证码
- (void)getVerificationCode {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user/smser",APP_HOST];
    if (![self checkMobile]) {
        return;
    }
    _timer = [YYTimer timerWithTimeInterval:1 target:self selector:@selector(countDown) repeats:YES];
    
    [GCZAFNetWorking POST:urlString params:@{@"phone" : _registerView.phoneNumberTextField.text} success:^(NSDictionary *response) {
        DLog(@"%@", response[@"message"]);
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        DLog(@"获取验证码失败%@", error);
    }];
    
}

- (void)countDown {
    static int timeout = 60;
    timeout--;
    if (timeout == 45) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"未收到验证码?" message:@"是否发送语音验证码" preferredStyle:(UIAlertControllerStyleAlert)];
        @weakify(self);
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [weak_self getVoiceVerificationCodeWithPhone];
            [alertVC dismissViewControllerAnimated:YES completion:nil];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            [alertVC dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:confirmAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    static NSString *btnTitle = @"";
    if (timeout == 0) {
        [_timer invalidate];
        btnTitle = @"获取验证码";
        timeout = 60;
        _registerView.verificationCodeBtn.enabled = YES;
        [_registerView.verificationCodeBtn setTitle:btnTitle forState:(UIControlStateNormal)];
    } else {
        _registerView.verificationCodeBtn.enabled = NO;
        btnTitle = [NSString stringWithFormat: @"%d后可重发", timeout];
        [_registerView.verificationCodeBtn setTitle:btnTitle forState:(UIControlStateNormal)];
    }
}

#pragma mark- 获取语音验证码
- (void)getVoiceVerificationCodeWithPhone {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/user/audio-smser",APP_HOST];
    if (![self checkMobile]) {
        return;
    }
    [GCZAFNetWorking POST:urlString params:@{@"phone" : _registerView.phoneNumberTextField.text} success:^(NSDictionary *response) {
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
    }];
}

#pragma mark - 获取头部的图片
- (void)getTopImage {
    NSString *urlString = [NSString stringWithFormat:@"%@//api/web/index.php/v1/doujin/random-doujin",APP_HOST];
    [GCZAFNetWorking GET:urlString success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSString *authorStr = [NSString stringWithFormat:@"作者:%@", response[@"result"][@"author"]];
            if ([response[@"result"][@"share_pics"] containsString:@"http"]) {
//                NSURL *imgUrl = [NSURL URLWithString:response[@"result"][@"share_pics"]];
                _registerView.authorLabel.text = authorStr;
//                [_registerView.topImageView yy_setImageWithURL:imgUrl options:(YYWebImageOptionUseNSURLCache)];
                _registerView.topImageView.yy_imageURL = [NSURL URLWithString:[response[@"result"][@"share_pics"] stringByAppendingString:@"?x-oss-process=style/ios_doujin_50"]];
            }
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
    
}

- (BOOL)checkMobile {
    NSString *phoneNumber = _registerView.phoneNumberTextField.text;
    if (!phoneNumber || phoneNumber.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        return NO;
    }
    return YES;
}
- (void)dealloc {
    DLog(@"%s", __func__);
    [_timer invalidate];
    _timer = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
